import { api } from '../api';
import type {
  Video,
  VideoListResponse,
  VideoGenerateRequest,
  VideoGenerateResponse,
  VideoSyncResult,
} from '../types/video';

// 视频服务
class VideoService {
  // 获取视频列表
  async getVideos(page = 1, pageSize = 20): Promise<VideoListResponse> {
    const response = await api.get<{ rows: Video[]; count: number }>('/videos', {
      params: { page, pageSize },
    });
    // 后端使用统一列表格式：{ rows: [...], count: number }
    const listData = response;
    return {
      videos: listData.rows || [],
      total: listData.count || 0,
      page,
      pageSize,
    };
  }

  // 获取视频详情
  async getVideoDetail(videoId: string): Promise<Video> {
    const response = await api.get<Video>(`/videos/${videoId}`);
    return response;
  }

  // 搜索视频
  async searchVideos(query: string, status?: string, type?: string): Promise<VideoListResponse> {
    const response = await api.get<{ rows: Video[]; count: number }>('/videos/search', {
      params: { query, status, type },
    });
    // 后端使用统一列表格式：{ rows: [...], count: number }
    const listData = response;
    return {
      videos: listData.rows || [],
      total: listData.count || 0,
    };
  }

  // 删除视频（软删除）
  async deleteVideo(videoId: string): Promise<void> {
    await api.delete(`/videos/${videoId}`);
  }

  // 批量删除视频
  async deleteVideos(videoIds: string[]): Promise<void> {
    await api.post('/videos/batch-delete', { video_ids: videoIds });
  }

  // 同步活跃账户的视频
  async syncVideos(): Promise<VideoSyncResult> {
    const response = await api.post<{ result: VideoSyncResult; status: string }>(`/sync/videos`);
    // 同步接口返回的是带有 result 和 status 的格式
    return response.result;
  }

  // 同步指定账户视频（保留向后兼容）
  async syncAccountVideos(accountId: number): Promise<VideoSyncResult> {
    const response = await api.post<{ result: VideoSyncResult; status: string }>(
      `/sync/account/${accountId}/videos`
    );
    // 同步接口返回的是带有 result 和 status 的格式
    return response.result;
  }

  // 生成视频（预留接口）
  async generateVideo(request: VideoGenerateRequest): Promise<VideoGenerateResponse> {
    const response = await api.post<VideoGenerateResponse>('/videos/generate', request);
    return response;
  }

  // 获取视频生成状态（从数据库）
  async getVideoGenerationStatus(videoId: string): Promise<Video> {
    const response = await api.get<Video>(`/videos/${videoId}/status`);
    return response;
  }

  // 从HeyGen API查询视频真实状态
  async checkVideoStatusFromAPI(videoId: string): Promise<{
    video_id: string;
    status: string;
    progress: number;
    message: string;
    created_at: number;
    duration?: number;
    video_url?: string;
    thumbnail_url?: string;
    caption_url?: string;
    error?: Record<string, unknown>;
  }> {
    const response = await api.get<{
      video_id: string;
      status: string;
      progress: number;
      message: string;
      created_at: number;
      duration?: number;
      video_url?: string;
      thumbnail_url?: string;
      caption_url?: string;
      error?: Record<string, unknown>;
    }>(`/videos/${videoId}/check-status`);
    return response;
  }

  // 下载视频
  async downloadVideo(videoUrl: string, filename: string): Promise<void> {
    const a = document.createElement('a');
    a.href = videoUrl;
    a.download = filename;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  // 获取视频统计信息
  async getVideoStats(accountId?: number): Promise<{
    total: number;
    completed: number;
    processing: number;
    failed: number;
    draft: number;
  }> {
    const response = await api.get<{
      total: number;
      completed: number;
      processing: number;
      failed: number;
      draft: number;
    }>('/videos/stats', {
      params: { account_id: accountId },
    });
    return response;
  }
}

export default new VideoService();
